<?php
/*
 * 如果先插入逆向关系（friend_id, user_id），再插入顺向关系，
 * 因为要返回顺向关系的记录id，所以要判断两条是否都成功写入数据库需要判断
 * 目前就先插入逆向关系，不管它成功不成功，再插入顺向关系，
 * 顺向关系成功就成功，失败就失败，返回顺向关系的记录id
 */
require_once("../data/db_connection.php");
require_once("../constants.php");
require_once("../Utils.php");

$db = new db();
$return_id = -1;
$_id = getFinalValue($_POST[PARAM_USER_ID]);
$friend_id = getFinalValue($_POST[PARAM_FRIEND_ID]);

function sendRelationRequest($db, $_id, $friend_id) {
	$return_id = -1;
	// 如果自己已经被别人邀请过，服务端自动把记录状态修改
	$sql1 = "SELECT _id FROM pTableRelation WHERE pUserId = " . $friend_id . " and pFriendId = " . $_id;
	if($result= $db->query($sql1)) {
		if	($row = $result->fetch_assoc()) {
			$row_id = $row['_id'];
			$sql1 = "UPDATE pTableRelation SET pRelationState = 0 WHERE _id = " . $row_id;	
		}
		$sql1 = "UPDATE pTableRelation SET pRelationState = 0 WHERE pUserId = " . $_id . " and pFriendId = " . $friend_id;
		$return_id = $db->update_get_id($sql1);
	} else {
		$sql2 = array("INSERT INTO pTableRelation VALUES (NULL, " . $friend_id . ", " . $_id .  ", 2)",
			 	"INSERT INTO pTableRelation VALUES (NULL, " . $_id . ", " . $friend_id .  ", 1)");

		// 如开始注释所述，忽略第一条insert语句执行的结果
		for ($i = 0; $i < 2; $i++) {
			$return_id = $db->insert_get_id($sql2[$i]);
		}
	}
	return $return_id;
}

$return_id = sendRelationRequest($db, $_id, $friend_id)
/*
 * 如果是n说明返回的是记录id
 * 如果是0说明是空值
 */
echo $return_id;
?>